<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover"
    />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>GLTFLoader with Physics</title>
    <link rel="stylesheet" href="/css/examples.css?ver=1.0.0" />
    <script src="/js/examples.js?ver=1.1.1"></script>
    <script src="/lib/three.min.js"></script>
    <script src="/lib/GLTFLoader.js"></script>
    <script src="/lib/enable3d/enable3d.ammoPhysics.0.22.0.min.js"></script>
    <script src="/lib/OrbitControls.js"></script>
  </head>

  <body>
    <script>
      const { AmmoPhysics, PhysicsLoader } = ENABLE3D

      const MainScene = () => {
        const scene = new THREE.Scene()
        scene.background = new THREE.Color(0xf0f0f0)

        const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 1000)
        camera.position.set(6, 6, 12)

        const renderer = new THREE.WebGLRenderer()
        renderer.setSize(window.innerWidth, window.innerHeight)
        document.body.appendChild(renderer.domElement)

        const controls = new THREE.OrbitControls(camera, renderer.domElement)

        scene.add(new THREE.HemisphereLight(0xffffbb, 0x080820, 1))
        scene.add(new THREE.AmbientLight(0x666666))
        const light = new THREE.DirectionalLight(0xdfebff, 1)
        light.position.set(50, 200, 100)
        light.position.multiplyScalar(1.3)

        // initialize physics
        const physics = new AmmoPhysics(scene)
        physics.debug.enable(true)

        // add a ground
        physics.add.ground({ width: 20, height: 20 })

        // add suzanne with physics
        const loader = new THREE.GLTFLoader().load('/assets/glb/suzanne.glb', function (gltf) {
          const suzanne = gltf.scene.children[0]
          suzanne.position.setY(5)

          suzanne.traverse(child => {
            if (child.isMesh) {
              child.castShadow = child.receiveShadow = false
              child.material.metalness = 0
              child.material.roughness = 1
            }
          })

          scene.add(suzanne)
          physics.add.existing(suzanne, { shape: 'convex' })
        })

        const clock = new THREE.Clock()

        const animate = () => {
          // update physics
          physics.update(clock.getDelta() * 1000)
          // update the physics debugger
          physics.updateDebugger()

          renderer.render(scene, camera)
          requestAnimationFrame(animate)
        }
        requestAnimationFrame(animate)
      }
      PhysicsLoader('/lib/ammo/kripken', () => MainScene())

      console.log(`three.js version "${THREE.REVISION}"`)
    </script>
  </body>
</html>
